package com.pachong.android.baseuicomponent;


import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;

import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.view.BottomLoadStateView;

import java.util.ArrayList;
import java.util.List;

/**
 * BaseComponentHelper
 *
 * @author Vivi Peng
 */
public class BaseComponentHelper {

    private Context mContext;
    /**
     * 使用该Helper的Component
     */
    private Object mComponent;
    private boolean mAutoLoading = true; // 自动加载
    private int mTriggerLoadItemCount = 3; // 触发下载的item数量；剩下多少项的时候自动加载
    private List<RecyclerView.ItemDecoration> mItemDecorations = new ArrayList();

    private RecyclerView mRecyclerView;

    private BottomLoadStateView mBottomLoadStateView;

    protected LoadState mLoadState = LoadState.IDLE;

    public BaseComponentHelper(Context context, Object component) {
        mContext = context;
        mComponent = component;
    }


    public boolean isEmpty() {
        if (getAdapter() != null) {
            if (getAdapter().getDataCount() > 0 || getAdapter().hasHeaderView()) {
                return false;
            }
        }
        return true;
    }


    public void setBottomLoadStateView(final ILoadable loadable, final BottomLoadStateView stateView) {
        mBottomLoadStateView = stateView;
        getAdapter().setLoaidngLayout(mBottomLoadStateView);
        if (stateView != null) {
            stateView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (stateView.getState() == LoadState.ERROR
                            || stateView.getState() == LoadState.IDLE) {
                        loadable.startLoading();
                    }

                }
            });
        }
    }

    /**
     * 开始加载,由User调用
     */
    public void startLoading(Context context, IComponentStatable ics, ILoadable loadable) {
        if (NetUtils.getNetworkStatus(context) == NetUtils.NETWORK_STATE_IDLE) {
            if (isEmpty() || (getAdapter().getDataCount() == 0 && getAdapter().hasHeaderView())) {
                ics.setState(CompState.EMPTY_INVALID_NEWWORK);
            } else {
                ics.setState(CompState.DATA);
                setLoadState(LoadState.INVALID_NETWORK);
            }
            return;
        }
        if (isEmpty()) {
            ics.setState(CompState.EMPTY_REFRESHING);
        } else {
            ics.setState(CompState.DATA);
            setLoadState(LoadState.LOADING);
        }
        loadable.onStartLoading();
    }


    public void setHeaderView(RecyclerViewBaseAdapter adapter, View headerView) {
        if (headerView != null) {
            RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(
                    RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT);
            headerView.setLayoutParams(lp);
            adapter.setHeaderView(headerView);
        }


    }


    public void initRecyclerView(Context context, final ILoadable loadable) {

        RecyclerView.ItemAnimator itemAnimator = mRecyclerView.getItemAnimator();
//        itemAnimator.setSupportsChangeAnimations(true);
        mRecyclerView.setHasFixedSize(true);

        RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(context,
                DividerItemDecoration.VERTICAL_LIST);

        addItemDecoration(itemDecoration);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                // 自动加载
                if (!mAutoLoading) {
                    return;
                }

                if (mRecyclerView.getAdapter() != null && mLoadState == LoadState.IDLE) {
                    // 如果itemCount超过2*mTriggerLoadItemCount个
                    if (mRecyclerView.getAdapter().getItemCount() > 2 * mTriggerLoadItemCount) {
                        if (mRecyclerView.getLayoutManager() != null) {
                            View item = mRecyclerView.getLayoutManager().findViewByPosition(mRecyclerView.getAdapter().getItemCount()
                                    - mTriggerLoadItemCount);
                            if (item != null && item.getVisibility() == View.VISIBLE) {
                                /*Log.i(TAG, "item " + (getAdapter().getItemCount() - mTriggerLoadItemCount)
                                        + "is visible, start loading");*/
                                loadable.startLoading();
                            }
                        }
                    }
                }

                super.onScrolled(recyclerView, dx, dy);
            }

        });
    }


    /**
     * 设置触发自动加载的item的剩余数量
     *
     * @param itemCount
     */
    public void setTriggerLoadItemCount(int itemCount) {
        mTriggerLoadItemCount = itemCount;
    }

    /**
     * 是否自动加载
     *
     * @param auto
     */
    public void setAutoLoading(boolean auto) {
        mAutoLoading = auto;
    }


    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    public void setRecyclerView(RecyclerView rv) {
        mRecyclerView = rv;
    }

    public RecyclerViewBaseAdapter getAdapter() {
        if (mRecyclerView.getAdapter() == null) {
            return null;
        }
        return (RecyclerViewBaseAdapter) mRecyclerView.getAdapter();
    }

    public void clearDecorations() {
        if (mItemDecorations != null && mItemDecorations.size() > 0) {
            for (RecyclerView.ItemDecoration itemDec : mItemDecorations) {
                getRecyclerView().removeItemDecoration(itemDec);
            }
        }
    }

    public void addItemDecoration(RecyclerView.ItemDecoration itemDecoration) {
        mItemDecorations.add(itemDecoration);
        getRecyclerView().addItemDecoration(itemDecoration);
    }

    public void setLoadState(LoadState state) {
        if (mLoadState != state) {
            mLoadState = state;
            if (mBottomLoadStateView != null) {
                mBottomLoadStateView.setState(mLoadState);
            }
        }

        if (mComponent instanceof IComponentStatable)  {
            IComponentStatable comp = (IComponentStatable) mComponent;
            if (isEmpty()) {
                comp.setState(CompState.EMPTY);
            } else {
                comp.setState(CompState.DATA);
            }
        }

    }

    public void setAdapter(RecyclerViewBaseAdapter adapter, final IComponentStatable ics, AdapterView.OnItemClickListener itemClickListener, AdapterView.OnItemLongClickListener itemLongClickListener) {
        if (adapter != null) {
            getRecyclerView().setAdapter(adapter);
            getAdapter().setOnItemClickListener(itemClickListener);
            getAdapter().setOnItemLongClickListener(itemLongClickListener);
            getAdapter().registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {

                @Override
                public void onItemRangeInserted(int positionStart, int itemCount) {
                    if (isEmpty()) {
                        ics.setState(CompState.EMPTY);
                    } else {
                        ics.setState(CompState.DATA);
                    }
                    super.onItemRangeInserted(positionStart, itemCount);
                }


                @Override
                public void onItemRangeRemoved(int positionStart, int itemCount) {
                    if (isEmpty()) {
                        ics.setState(CompState.EMPTY);
                    } else {
                        ics.setState(CompState.DATA);
                    }
                    super.onItemRangeRemoved(positionStart, itemCount);
                }
            });

        } else {
        }
    }

    public View createRecyclerContentView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_recyclerview, null);
        RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
        setRecyclerView(rv);
        return view;
    }
}
